package com.qf.handler;

import com.alibaba.fastjson.JSON;
import com.qf.pojo.Result;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.nio.charset.StandardCharsets;

//当路由失败后,会执行这个处理器的handle方法.可以在这个方法中实现友好提示
@Component
@Order(-5)
public class MyWebExceptionHandler implements WebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {

        //获取请求的uri
        URI uri = exchange.getRequest().getURI();

        Result result = Result.error("请求不合法,请检查路径或者参数.当年请求的uir为:" + uri.toString());
        String json = JSON.toJSONString(result);

        //解决中文响应乱码问题
        exchange.getResponse().getHeaders().add("content-type","text/html;charset=utf-8");

        //将以上信息响应到页面
        DataBuffer dataBuffer = exchange.getResponse().bufferFactory().wrap(json.getBytes(StandardCharsets.UTF_8));
        //这个Mono对象就是我们writeWith需要的publisher对象
        Mono<DataBuffer> mono = Mono.just(dataBuffer);
        return exchange.getResponse().writeWith(mono);
    }
}
